# == Schema Information
# Schema version: 6
#
# Table name: blogs
#
#  id               :integer(11)     not null, primary key
#  user_id          :integer(11)     
#  about            :string(255)     
#  custom           :string(255)     
#  entries_per_page :integer(11)     default(10)
#  recent_entries   :integer(11)     default(10)
#  recent_comments  :integer(11)     default(10)
#  title            :string(255)     default("my blog")
#  subtitle         :string(255)     default("my another blog")
#  abstract_length  :integer(11)     default(100)
#

class Blog < ActiveRecord::Base
  # relations
  belongs_to :user
  has_many :categories, :order => :position
  
  
  #  has_many :entries, :finder_sql => 'SELECT DISTINCT e.* ' +
  #    'FROM entries e, categories c ' +
  #    'WHERE c.blog_id = #{id} AND e.category_id = c.id ' +
  #    'ORDER BY e.created_at DESC' do
  #    def recent(count)
  #      find(:all, :limit => count)
  #    end
  #  end
  
  has_many :entries, :through => :categories, :order => "created_at DESC"
  
  has_many :comments, :class_name => "Comment", :finder_sql => 'SELECT DISTINCT cm.* ' +
    'FROM comments cm, entries e, categories c ' +
    'WHERE c.blog_id = #{id} AND e.category_id = c.id AND cm.commentable_id = e.id ' +
    'ORDER BY cm.created_at DESC'
  
  has_many :links
  
  has_many :blocks
  has_many :visible_blocks, :class_name => "Block", :conditions => ["visible = ?", true]
  
  # validations
  
  def latest_entries(count)
    self.entries.find(:all, :limit => count)
  end
  
  def latest_comments(count)
    Comment.latest_comments_on(self.user, count)
  end
  
  def entries_created_in(year, month)
    self.entries.find(:all, 
      :conditions => ["YEAR(created_at) = ? AND MONTH(created_at) = ?", year, month])
  end
  
  def latest_archive_links(count = nil)
    now = Time.now
    year = now.year
    month = now.month
    
    count_of_month = (year - self.user.created_at.year) * 12 + (month - self.user.created_at.month + 1)
    
    if count.nil?
      monthes = count_of_month
    else
      monthes = count < count_of_month ? count : count_of_month
    end
    
    month_list = Array.new
    monthes.times do
      month_list << {:year => year, :month => month}
      if month > 1
        month -= 1
      else
        month = 12
        year -= 1
      end
    end
    month_list
  end
end
